package cn.hfatec.shms.system.role.action;

import cn.hfatec.JsonResponse;
import cn.hfatec.Page;
import cn.hfatec.Table;
import cn.hfatec.constants.SysContant;
import cn.hfatec.freemarker.FreeMarkerUtil;
import cn.hfatec.shms.base.ShmsBaseAction;
import cn.hfatec.shms.cache.CodeInfoCache;
import cn.hfatec.shms.constants.ShmsConstant;
import cn.hfatec.shms.enums.CodeType;
import cn.hfatec.shms.system.authData.model.AuthData;
import cn.hfatec.shms.system.authData.model.AuthDataParams;
import cn.hfatec.shms.system.authData.service.AuthDataService;
import cn.hfatec.shms.system.homeConfiguration.model.HomeConfiguration;
import cn.hfatec.shms.system.homeConfiguration.model.HomeConfigurationParams;
import cn.hfatec.shms.system.homeConfiguration.service.HomeConfigurationService;
import cn.hfatec.shms.system.menu.model.MenuView;
import cn.hfatec.shms.system.menu.service.MenuService;
import cn.hfatec.shms.system.module.model.Module;
import cn.hfatec.shms.system.module.model.ModuleParams;
import cn.hfatec.shms.system.module.service.ModuleService;
import cn.hfatec.shms.system.role.model.Role;
import cn.hfatec.shms.system.role.model.RoleParams;
import cn.hfatec.shms.system.role.service.RoleService;
import cn.hfatec.shms.system.roleAuth.service.RoleAuthService;
import cn.hfatec.shms.system.roleHome.service.RoleHomeService;
import cn.hfatec.shms.system.roleMenu.service.RoleMenuService;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;


/**
 * @author hfatec codegen
 * @version 1.0
 *          <p/>
 *          the JAVA code is generate by middlegen
 */
@Controller
@RequestMapping("/system/role")
public class RoleAction extends ShmsBaseAction {

    //服务层
    @Resource(name = "RoleService")
    private RoleService roleService;

    @Resource(name = "AuthDataService")
    private AuthDataService authDataService;

    @Resource(name = "RoleAuthService")
    private RoleAuthService roleAuthService;

    @Resource(name = "MenuService")
    private MenuService menuService;

    @Resource(name = "RoleMenuService")
    private RoleMenuService roleMenuService;

    @Resource(name = "RoleHomeService")
    private RoleHomeService roleHomeService;

    @Resource(name = "HomeConfigurationService")
    private HomeConfigurationService homeConfigurationService;

    @Resource(name = "ModuleService")
    private ModuleService moduleService;

    /**
     * 查询列表
     */
    @RequestMapping("/list")
    public String list(RoleParams roleParams, Page page, Model model) {

        Table table = roleService.queryRoleTable(roleParams, page);
        model.addAttribute("rolesTable", table);
        model.addAttribute("roleParams", roleParams);
        return "/system/role/list";
    }

    /**
     * 异步查询列表
     */
    @RequestMapping("/ajaxList")
    @ResponseBody
    public String ajaxList(RoleParams roleParams, Page page, Model model) {
        try {
            list(roleParams, page, model);
            return new JsonResponse<Map>(JsonResponse.RETURN_SUCCESS, "", FreeMarkerUtil.render("/system/role/table", model)).toString();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonResponse.error;
    }

    /**
     * 跳转到新增页
     */
    @RequestMapping("/goAdd")
    @ResponseBody
    public String goAdd(Model model) {
        try {
            Role role = new Role();
            model.addAttribute("role", role);
            return new JsonResponse<Map>(JsonResponse.RETURN_SUCCESS, "", FreeMarkerUtil.render("/system/role/form", model)).toString();

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonResponse.error;
    }

    /**
     * 跳转到编辑页
     */
    @RequestMapping("/goEdit")
    @ResponseBody
    public String goEdit(Integer id, Model model) {

        try {
            Role role = roleService.getRole(id);
            model.addAttribute("role", role);
            return new JsonResponse<Map>(JsonResponse.RETURN_SUCCESS, "", FreeMarkerUtil.render("/system/role/form", model)).toString();

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonResponse.error;
    }

    /**
     * 根据IDs删除数据
     */
    @RequestMapping("/delete")
    @ResponseBody
    public String deleteRole(String ids) {
        try {
            List<String> idList = new ArrayList<String>();
            if (ids.length() > 0) {
                idList = Arrays.asList(ids.split(","));
            }
            roleService.deleteRoleBatch(idList);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("数据" + ids + "删除异常！");
            return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, SysContant.DELETE_ERROR_MESSAGE).toString();
        }
        return new JsonResponse(JsonResponse.RETURN_SUCCESS, SysContant.DELETE_SUCCESS_MESSAGE).toString();
    }

    /**
     * 保存数据
     */
    @RequestMapping("/save")
    @ResponseBody
    public String saveRole(@Valid Role role, BindingResult result) {

        try {
            if (result.hasErrors()) {
                return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, result.getAllErrors().get(0).getDefaultMessage()).toString();
            }
            roleService.saveRole(role);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("数据Role保存异常！");
            return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, SysContant.SAVE_ERROR_MESSAGE).toString();
        }
        return new JsonResponse<String>(JsonResponse.RETURN_SUCCESS, SysContant.SAVE_SUCCESS_MESSAGE).toString();
    }


    /**
     * 跳转到分配权限页面
     *
     * @param roleId
     * @param model
     * @return
     */
    @RequestMapping("/goAssignAuth")
    public String goAssignAuth(String roleId, Model model) {
        try {
            List<Module> allModuleList = moduleService.queryModuleTable(new ModuleParams());


            String moduleId = "";
            //过滤顶级根模块
            for(Module module : allModuleList){
                if(StringUtils.isNotEmpty(module.getParentModuleId()) && module.getParentModuleId().equals(ShmsConstant.ROOT_MODULE_ID)){
                    moduleId = module.getModuleId();
                    break;
                }
            }


            List ModuleList = moduleService.getModuleViewList(moduleId, allModuleList);

            List assignAuthList = roleAuthService.queryAuthListByRoleId(roleId);
            List<AuthData> authDatasList = authDataService.queryAuthDataList(new AuthDataParams());


            model.addAttribute("assignAuthList", assignAuthList);
            model.addAttribute("roleId", roleId);
            model.addAttribute("modulesTable", ModuleList);

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return "/system/role/assignAuthData";
    }

    /**
     * 为角色分配权限
     *
     * @param roleId
     * @param ids
     * @return
     */
    @RequestMapping("/assignAuth")
    @ResponseBody
    public String assignAuth(String roleId, @RequestParam(value = "authIds", required = false) String[] ids) {

        try {
            roleAuthService.assignAuth(roleId, ids);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("角色权限分配保存异常！");
            return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, SysContant.SAVE_ERROR_MESSAGE).toString();
        }
        return new JsonResponse<String>(JsonResponse.RETURN_SUCCESS, SysContant.SAVE_SUCCESS_MESSAGE).toString();
    }

    /**
     * 跳转到菜单分配界面
     *
     * @param roleId
     * @param model
     * @return
     */
    @RequestMapping("/goAssignMenu")
    @ResponseBody
    public String goAssignMenu(String roleId, Model model) {

        try {
            List<MenuView> menuViewList = menuService.queryAllMenuList();
            List assignMenuList = roleMenuService.queryRoleMenuByRoleId(roleId);
            model.addAttribute("menuViewList", menuViewList);
            model.addAttribute("assignMenuList", assignMenuList);
            model.addAttribute("roleId", roleId);
            return new JsonResponse<Map>(JsonResponse.RETURN_SUCCESS, "", FreeMarkerUtil.render("/system/role/assignMenu", model)).toString();

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonResponse.error;
    }

    /**
     * 分配角色菜单权限
     *
     * @param roleId
     * @param ids
     * @return
     */
    @RequestMapping("/assignMenu")
    @ResponseBody
    public String assignMenu(String roleId, String[] ids) {

        try {
            roleMenuService.assignMenu(roleId, ids);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("角色权限分配保存异常！");
            return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, SysContant.SAVE_ERROR_MESSAGE).toString();
        }
        return new JsonResponse<String>(JsonResponse.RETURN_SUCCESS, SysContant.SAVE_SUCCESS_MESSAGE).toString();
    }

    /**
     * 跳转到首页图标分配页面
     *
     * @param roleId
     * @param model
     * @return
     */
    @RequestMapping("/goAssignHome")
    @ResponseBody
    public String goAssignHome(String roleId, Model model) {

        try {

            List assignHomeList = roleHomeService.queryHomeListByRoleId(roleId);
            List<HomeConfiguration> roleHomeList = homeConfigurationService.queryHomeConfigurationList(new HomeConfigurationParams());

            model.addAttribute("assignHomeList", assignHomeList);
            model.addAttribute("homeConfigurationList", roleHomeList);
            model.addAttribute("roleId", roleId);
            model.addAttribute("confTypeList", CodeInfoCache.getCodeInfo(CodeType.CONF_TYPE));
            return new JsonResponse<Map>(JsonResponse.RETURN_SUCCESS, "", FreeMarkerUtil.render("/system/role/assignRoleHome", model)).toString();

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonResponse.error;
    }

    /**
     * 为角色分配首页图标
     *
     * @param roleId
     * @param ids
     * @param allIds
     * @return
     */
    @RequestMapping("/assignHome")
    @ResponseBody
    public String assignHome(String roleId, @RequestParam(value = "confIds", required = false) String[] ids, String[] allIds) {

        try {
            System.out.println(roleId);
            System.out.println(Arrays.toString(ids));
            System.out.println(Arrays.toString(allIds));
            roleHomeService.assignHome(roleId, ids, allIds);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("首页图标分配保存异常！");
            return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, SysContant.SAVE_ERROR_MESSAGE).toString();
        }
        return new JsonResponse<String>(JsonResponse.RETURN_SUCCESS, SysContant.SAVE_SUCCESS_MESSAGE).toString();
    }
}
